package cn.itcast.bos.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.service.AreaService;
import cn.itcast.bos.utils.PinYin4jUtils;
import cn.itcast.bos.web.action.common.BaseAction;

@ParentPackage("json-default")
@Namespace("/")
@Scope("prototype")
@Controller
public class AreaAction extends BaseAction<Area> {

	private static final long serialVersionUID = 1L;

	@Autowired
	private AreaService areaService;

	// 使用struts2文件上传过滤器功能
	private File file;
	private String fileFileName;
	private String fileContentType;

	public void setFile(File file) {
		this.file = file;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	// 保存快递员信息
	@Action(value = "area_batchImport", results = { @Result(name = "success", type = "json") })
	public String batchImport() throws Exception {
		// System.out.println(file);
		// System.out.println(fileFileName);
		// System.out.println(fileContentType);
		/** 解析上传的exel文件 */
		// 定义一个数组用来存放解析的exel数据
		List<Area> areaList = new ArrayList<Area>();
		// 加载exel文件对象
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
		// 读取一个sheet
		HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
		// 读取每一行对应的数据
		for (Row row : sheet) {
			// 如果是第一行表头就跳过
			if (row.getRowNum() == 0) {
				continue;
			}
			// 跳过空行的值
			if (row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
				continue;
			}
			Area area = new Area();
			area.setId(row.getCell(0).getStringCellValue());
			area.setProvince(row.getCell(1).getStringCellValue());
			area.setCity(row.getCell(2).getStringCellValue());
			area.setDistrict(row.getCell(3).getStringCellValue());
			area.setPostcode(row.getCell(4).getStringCellValue());
			/** 基于pinyin4j生成城市编码和简码 */
			String province = area.getProvince();
			String city = area.getCity();
			String district = area.getDistrict();
			province = province.substring(0, province.length() - 1);// 去掉省
			city = city.substring(0, city.length() - 1);// 去掉市
			district = district.substring(0, district.length() - 1);
			// 生成简码
			String[] headArr = PinYin4jUtils.getHeadByString(province + city + district);
			System.out.println(headArr);
			// 将生成的简码字符数组拼接成字符串
			StringBuilder stringBuilder = new StringBuilder();
			for (String string : headArr) {
				stringBuilder.append(string);
			}
			String shortCode = stringBuilder.toString();
			area.setShortcode(shortCode);
			// 生成城市编码
			String cityCode = PinYin4jUtils.hanziToPinyin(city, "");
			area.setCitycode(cityCode);
			areaList.add(area);
		}
		areaService.save(areaList);
		return SUCCESS;
	}
	
	
	@Action(value="area_pageQueryCondition",results={@Result(name="success",type="json")})
	public String pageQueryCondition() {
		Pageable pageable = new PageRequest(page - 1, rows);

		// 定义specification
		Specification<Area> specification = new Specification<Area>() {

			@Override
			public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				Predicate predicate = null;
				// 定义list用来封装多个查询条件
				List<Predicate> list = new ArrayList<Predicate>();
				// 省
				if (StringUtils.isNotBlank(model.getProvince())) {
					Predicate p = cb.like(root.get("province").as(String.class), "%"+model.getProvince()+"%");
					list.add(p);
				}
				// 市
				if (StringUtils.isNotBlank(model.getCity())) {
					Predicate p = cb.like(root.get("city").as(String.class), "%"+model.getCity()+"%");
					list.add(p);
				}

				// 县
				if (StringUtils.isNotBlank(model.getDistrict())) {
					Predicate p = cb.like(root.get("district").as(String.class), "%" + model.getDistrict() + "%");
					list.add(p);
				}

				// 构建条件组合
				if (list != null && list.size() > 0) {
					Predicate[] pArr = new Predicate[list.size()];
					predicate = cb.and(list.toArray(pArr));
				}
				return predicate;
			}
		};
		Page<Area> pageData = areaService.findPageDate(specification, pageable);
		
		pushPageDataToValueStack(pageData);
		
		return SUCCESS;
	}

	

}
